<?php
/**
 * (actions) 提货产品申请(撤回)
 */
namespace App\Admin\Actions\Shipping;

use App\Models\Shipping\SSkuApply;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
class SkuBatchRevoke extends BatchAction
{
    public $name = '撤回';

    public function handle(Collection $collection)
    {
        try{
            $count = 0;
            $shippingDate = SSkuApply::initShippingDate();
            $sDate = array_key_first($shippingDate);
            $eDate = array_key_last($shippingDate);
            foreach ($collection as $model) {
                if($model->status != 2){
                    continue;
                }
                DB::beginTransaction();

                //更新提货sku
                $model->status = 1; //未审批
                $flag = $model->save();
                if(!$flag){
                    DB::rollBack();
                    continue;
                }

                //更新提货申请（复原数量为(最后一次)上一次申请数量）
                $sca = SSkuApply::query()->where('area_id',$model->area_id)
                    ->where('psku_id',$model->psku_id)
                    ->where('shipping_date','>=',$sDate)
                    ->where('shipping_date','<=',$eDate)
                    ->get();
                $flag1 = false;
                foreach($sca as $_sca){
                    $_sca->apply_num = $_sca->last_apply_num;
                    $flag2 = $_sca->save();
                    if(!$flag2){
                        $flag1 = false;
                        break;
                    }
                    $flag1 = true;
                }
                if($flag1){
                    $count++;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            return $this->response()->success("成功撤回{$count}条记录！")->refresh();
        }catch (\Exception $e){
            report($e);
            return $this->response()->error('系统异常！');
        }
    }

    public function dialog()
    {
        $this->confirm('确定撤回？');
    }
}
